package com.devperson.io.nio;

import com.devperson.io.bio.InputUtils;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 功能描述:
 *
 * @author lixiaomeng
 * @date 2018/12/14
 */
public class NIOClientSocket {

    public static void main(String[] args) throws Exception {
        SocketChannel socketChannel = SocketChannel.open(); // 客户端打开一个Socket连接
        socketChannel.connect(new InetSocketAddress(9999)); // 客户端的Socket连接，监听的端口
        ByteBuffer buffer = ByteBuffer.allocate(100);
        boolean flag = true;
        while (flag) {
            buffer.clear();
            String inputInfo = InputUtils.getInputInfo("请输入请求信息");
            buffer.put(inputInfo.getBytes()); // 数据放入缓存中
            buffer.flip();

            // 客户端向服务端写入信息
            socketChannel.write(buffer);

            // 客户端在读取服务端返回的信息之前，先清空缓存
            buffer.clear();
            int readCount = socketChannel.read(buffer);
            System.err.println(new String(buffer.array(),0,readCount));

            if ("byebye".equalsIgnoreCase(inputInfo)) {
                flag = false;
            }

        }
        socketChannel.close();
    }
}
